package com.yinshan.avchatdemo.activity;

import android.Manifest;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import com.yinshan.avchatdemo.R;
import com.yinshan.avchatdemo.utils.SPUtils;
import com.yinshan.avchatdemo.utils.string.MD5;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthService;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.yinshan.avchatkit.AVChatKit;

import java.lang.ref.WeakReference;

import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.RuntimePermissions;

@RuntimePermissions
public class LoginActivity extends AppCompatActivity {

    private Button Login_OK;    //登陆按钮
    private EditText account;   //账号输入框
    private EditText password;  //密码输入框
    private static final int BASIC_PERMISSION_REQUEST_CODE = 100;
    private String token;
    private CheckBox needRecordPasswordCB;
    private Boolean needRecordPassword = false;

    private Context context;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        context = new WeakReference<Context>(this).get();
        //初始化界面
        initView();
        LoginActivityPermissionsDispatcher.requestPermissionWithPermissionCheck(this);
        //保存按钮点击事件
        needRecordPasswordCB.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                needRecordPassword = isChecked;
            }
        });

        Login_OK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String accid = account.getText().toString();
                //判断是否为demo的appkey，是就加MD5，不是就直接透传
                token = password.getText().toString();
                //实例化logininfo，执行登陆
                LoginInfo loginInfo = new LoginInfo(accid, tokenFromPassword(token));
                doLogin(loginInfo);
            }
        });

    }

    private LoginInfo getLoginInfo() {
        String account = (String) SPUtils.get(this, "YX_ACCOUNT", "");
        String token = (String) SPUtils.get(this, "YX_TOKEN", "");
        if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(token)) {
            return new LoginInfo(account, tokenFromPassword(token));
        } else {
            return null;
        }
    }

    private String tokenFromPassword(String password) {
        String appKey = readAppKey(this);
        boolean isDemo = "45c6af3c98409b18a84451215d0bdd6e".equals(appKey) ||
                "fe416640c8e8a72734219e1847ad2547".equals(appKey);

        return isDemo ? MD5.getStringMD5(password) : password;
    }
    private static String readAppKey(Context context) {
        try {
            ApplicationInfo appInfo = context.getPackageManager().getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (appInfo != null) {
                return appInfo.metaData.getString("com.netease.nim.appKey");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 界面初始化
     */
    private void initView() {

        Login_OK = findViewById(R.id.Login_OK);
        account = findViewById(R.id.account);
        password = findViewById(R.id.password);
        needRecordPasswordCB = findViewById(R.id.cb_checkbox);

        //从本地获取之前存储的logininfo
        LoginInfo loginInfo = getLoginInfo();

        if (loginInfo != null) {
            account.setText(loginInfo.getAccount());
            password.setText(loginInfo.getToken());
            needRecordPassword = true;
            needRecordPasswordCB.setChecked(true);
        }
    }


    /**
     * 执行登陆
     *
     * @param loginInfo
     */
    private void doLogin(LoginInfo loginInfo) {
        RequestCallback<LoginInfo> callback = new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo loginInfo) {
                Toast.makeText(LoginActivity.this, "登陆成功！", Toast.LENGTH_SHORT).show();
                AVChatKit.setAccount(loginInfo.getAccount());
                //判断是否需要本地存储密码(CheckBox打钩)
                if (needRecordPassword) {
                    SPUtils.put(LoginActivity.this, "YX_ACCOUNT", loginInfo.getAccount());
                    SPUtils.put(LoginActivity.this, "YX_TOKEN", loginInfo.getToken());
                } else {//删除文件
                    SPUtils.remove(LoginActivity.this, "YX_ACCOUNT");
                    SPUtils.remove(LoginActivity.this, "YX_TOKEN");
                }
                //跳转到拨打界面
                Intent intent = new Intent(LoginActivity.this, AVChatCallActivity.class);
                startActivity(intent);
                finish();
            }

            @Override
            public void onFailed(int i) {
                Toast.makeText(LoginActivity.this, "登陆失败，错误码：" + i, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onException(Throwable throwable) {
                Toast.makeText(LoginActivity.this, "登陆异常，" + throwable.toString(), Toast.LENGTH_SHORT).show();
            }
        };
        NIMClient.getService(AuthService.class).login(loginInfo).setCallback(callback);
    }

    /**
     * 点击空白位置 隐藏软键盘
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (null != this.getCurrentFocus()) {
            InputMethodManager mInputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
            return mInputMethodManager.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), 0);
        }
        return super.onTouchEvent(event);
    }

    @NeedsPermission({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void requestPermission() {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        LoginActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @OnShowRationale({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showRationale(final PermissionRequest request) {
        new AlertDialog.Builder(context).setTitle("提示")
                .setMessage("需要下列权限：\n相机：视频通话\n麦克风：视频通话传播语音\n文件读写：聊天传图")
                .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        request.proceed();
                    }
                }).show();
    }

    @OnPermissionDenied({Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO, Manifest.permission.CALL_PHONE, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void permissionDenied() {
        Toast.makeText(context, "部分权限未授予，将影响部分功能使用", Toast.LENGTH_LONG).show();
    }
}
